package com.vj.router.server.impl;

import com.vj.router.common.*;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class GatewayConnectionServiceImpl extends GatewayConnectionServiceGrpc.GatewayConnectionServiceImplBase {

    private static final Logger logger = LoggerFactory.getLogger(GatewayConnectionServiceImpl.class);

    @Override
    public void registerGatewayConnection(RegisterGatewayConnectionRequest request, StreamObserver<RegisterGatewayConnectionResponse> responseObserver) {
        String gatewayId = request.getGatewayId();

        try {
            logger.info("Registering connection for gateway: {}", gatewayId);

            // 在这里添加网关连接的实际处理逻辑，比如缓存或数据库操作
            // 例如: GatewayConnectionCacheUtil.add(gatewayId);

            RegisterGatewayConnectionResponse response = RegisterGatewayConnectionResponse.newBuilder()
                    .setMessage("Gateway connection registered successfully for gateway: " + gatewayId)
                    .build();

            responseObserver.onNext(response);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error("Error registering connection for gateway: " + gatewayId, e);
            RegisterGatewayConnectionResponse errorResponse = RegisterGatewayConnectionResponse.newBuilder()
                    .setMessage("Error registering connection: " + e.getMessage())
                    .build();
            responseObserver.onError(e);
        }
    }

    @Override
    public void unregisterGatewayConnection(UnregisterGatewayConnectionRequest request, StreamObserver<UnregisterGatewayConnectionResponse> responseObserver) {
        String gatewayId = request.getGatewayId();

        try {
            logger.info("Unregistering connection for gateway: {}", gatewayId);

            // 在这里添加网关注销的实际处理逻辑，比如从缓存或数据库中移除网关连接
            // 例如: GatewayConnectionCacheUtil.remove(gatewayId);

            UnregisterGatewayConnectionResponse response = UnregisterGatewayConnectionResponse.newBuilder()
                    .setMessage("Gateway connection unregistered successfully for gateway: " + gatewayId)
                    .build();

            responseObserver.onNext(response);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error("Error unregistering connection for gateway: " + gatewayId, e);
            UnregisterGatewayConnectionResponse errorResponse = UnregisterGatewayConnectionResponse.newBuilder()
                    .setMessage("Error unregistering connection: " + e.getMessage())
                    .build();
            responseObserver.onError(e);
        }
    }
}
